有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Jena中向rdflist/rdfcollection动态添加项

是否可以在Jena中将项目动态添加到RDFList? 比如:

RDFList list = model.createList(new RDFNode[] {});
//string with names of rdf classes
String[] parts = list.split("-");

for(int i = 0; i<parts.length; i++){
    OntClass oclass = model.getOntClass("http://example.org/"+parts[i]);  
    list.add(oclass);
}

我正在得到
com.hp.hpl.jena.rdf.model.EmptyListUpdateException: Attempt to add() to the empty list (rdf:nil)
提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    在没有看到所有代码和某些值的情况下,我们无法确定发生了什么,但我认为这里的问题是,您不能使用RDFList#add和一个列表,我认为这就是您一开始创建的内容。由于您正在创建一个没有元素的列表,因此应该返回rdf:nil,这是一个空列表。请注意RDFList#add的文档说明:

    If this list is the empty (nil) list, we cannot perform a side-effecting update without changing the URI of this node (from rdf:nil) to a blank-node for the new list cell) without violating a Jena invariant. Therefore, this update operation will throw an exception if an attempt is made to add to the nil list. Safe ways to add to an empty list include with(RDFNode) and cons(RDFNode).

    你没有提到你是否有例外

    在您的情况下,我认为最简单的方法是创建OntClasses数组,然后从中创建列表。也就是说,你可以这样做(未经测试):

    String[] parts = list.split("-");
    RDFNode[] elements = new RDFNode[parts.length];
    
    for(int i = 0; i<parts.length; i++){
        elements[i] = model.getOntClass("http://example.org/"+parts[i]);  
    }
    
    RDFList list = model.createList(elements);
    

    或者,如文档中所述,如果您想将与一起使用,您可以执行以下操作(同样,未经测试):

    RDFList list = model.createList(new RDFNode[] {});
    //string with names of rdf classes
    String[] parts = list.split("-");
    
    for(int i = 0; i<parts.length; i++){
        OntClass oclass = model.getOntClass("http://example.org/"+parts[i]);  
        list = list.with(oclass);
    }
    

    关于这方面的更多信息,你可能会发现我的this answer及其相关评论。你不是第一个和RDFLists有点冲突的人